package com.xdap.keymen.utils;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.atomic.AtomicInteger;

@Slf4j
public class SerialNumberGenerator {
    // 线程安全的计数器
    private static final AtomicInteger counter = new AtomicInteger(0);
    // 当天的毫秒值
    private static long currentDayMillis = System.currentTimeMillis() / (24 * 60 * 60 * 1000) * (24 * 60 * 60 * 1000);

    /**
     * 生成流水ID,每日不重复。
     *
     * @return
     */
    public static synchronized String generateSerialNumber(int length) {
        // 获取当前时间
        long now = System.currentTimeMillis();
        // 如果日期变了，重置计数器
        if (now / (24 * 60 * 60 * 1000) != currentDayMillis / (24 * 60 * 60 * 1000)) {
            log.info("流水ID生成器,重置计数器. now:{},currentDay:{}", now, currentDayMillis);
            counter.set(0);
            currentDayMillis = System.currentTimeMillis() / (24 * 60 * 60 * 1000) * (24 * 60 * 60 * 1000);
        }

        // 获取计数器值
        int count = counter.getAndIncrement();
        // 格式化计数器，保证固定位数
        // 拼接流水号
        return String.format("%0" + length + "d", count);
    }

}
